import chalk from 'chalk';
import shell from 'shelljs';
import { cmdExec, getParams } from '../utils';

const log = console.log;
const params = getParams();

export default async function commit() {
  let msg = '',
    branch = '';

  if (!params || (params && params.length === 0)) {
    log(chalk.red('指令不完整,请先补充指令'));
    shell.exit(1);
  }

  if (!shell.which('git')) {
    log(chalk.red('git暂未安装,请先安装git'));
    shell.exit(1);
  }

  msg = params[0];
  branch = params[1];

  if (msg === '-b') {
  if (!branch) {
    log(chalk.red('branch参数缺失,qps cm -b branch'));
    shell.exit(1);
  }
  await cmdExec('git pull');
  await cmdExec(`git rebase origin/${branch}`).catch(() => {
    chalk.red(`git rebase origin/${branch}失败,请在本地手动执行`);
  });
  // await cmdExec('git push');
  } else {
  await cmdExec('git add .');
  await cmdExec(`git commit -m '${msg}'`);
  await cmdExec('git pull');
  // await cmdExec('git push');
  }
}
